package abcy.cloud.syscoreserver.services.impls;

import abcy.cloud.blogcommon.builder.TypeBuilder;
import abcy.cloud.blogcommon.enums.ErrorCodeEnum;
import abcy.cloud.blogcommon.enums.SignEnum;
import abcy.cloud.blogcommon.resp.ResponseEntity;
import abcy.cloud.blogcommon.utils.CodeUtil;
import abcy.cloud.blogcommon.utils.ParamValidateUtil;
import abcy.cloud.blogcommon.utils.UUIDUtil;
import abcy.cloud.syscoreserver.dto.req.SysUserAddReqDto;
import abcy.cloud.syscoreserver.dto.req.SysUserSelectReqDto;
import abcy.cloud.syscoreserver.dto.resp.SysUserSelectRespDto;
import abcy.cloud.syscoreserver.entities.SysRolePermission;
import abcy.cloud.syscoreserver.entities.SysUser;
import abcy.cloud.syscoreserver.entities.SysUserPermission;
import abcy.cloud.syscoreserver.exception.InsertIntoDatabaseException;
import abcy.cloud.syscoreserver.exception.NotEmptyException;
import abcy.cloud.syscoreserver.mappers.SysUserMapper;
import abcy.cloud.syscoreserver.mappers.SysUserPermissionMapper;
import abcy.cloud.syscoreserver.services.SysUserService;
import com.alibaba.nacos.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserPermissionMapper sysUserPermissionMapper;


    @Override
    public boolean addSysUser(SysUserAddReqDto sysUserAddReqDto) {
        log.info("新增用户接口参数：{}", sysUserAddReqDto);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        boolean flag = false;
        if (sysUserAddReqDto == null || ParamValidateUtil.isAnyEmpty(sysUserAddReqDto.getUserName(), sysUserAddReqDto.getPassword())) {
            throw new NotEmptyException(ErrorCodeEnum.ERR_5000.getCode(), "用户名：username 为空或 密码：password为空");
        }
        String userId = UUIDUtil.UUID();
        String userCode = CodeUtil.codeGenerator(SignEnum.USER.getValue(), sysUserMapper.getMaxUserCode());
        SysUser sysUser = TypeBuilder.of(SysUser::new)
                .with(SysUser::setId, userId)
                .with(SysUser::setCode, userCode)
                .with(SysUser::setCreateTime, sdf.format(date))
                .with(SysUser::setUpdateTime, sdf.format(date))
                .with(SysUser::setIsDel, sysUserAddReqDto.getIsDel())
                .with(SysUser::setEmail, sysUserAddReqDto.getEmail())
                .with(SysUser::setPhone, sysUserAddReqDto.getPhone())
                .with(SysUser::setUserName, sysUserAddReqDto.getUserName())
                .with(SysUser::setPassword, new BCryptPasswordEncoder().encode(sysUserAddReqDto.getPassword()))
                .with(SysUser::setIsDel, false).build();
        try {
            log.info("数据库新增对象数据：{}", sysUser);
            sysUserMapper.insert(sysUser);
        } catch (Exception e) {
            throw new InsertIntoDatabaseException(ErrorCodeEnum.ERR_5001.getCode(), "插入数据库异常" + e);
        }
        if(Objects.nonNull(sysUserAddReqDto.getPermissions())) {
            List<String> permissions = Arrays.asList(sysUserAddReqDto.getPermissions().split(","));
            if(CollectionUtils.isNotEmpty(permissions)) {
                for (String permission : permissions) {
                    SysUserPermission sysUserPermission = new SysUserPermission();
                    sysUserPermission.setId(UUIDUtil.UUID());
                    sysUserPermission.setUserId(userId);
                    sysUserPermission.setPermissionId(permission);
                    sysUserPermission.setCreateTime(date);
                    sysUserPermissionMapper.insert(sysUserPermission);
                }
            }
        }
        return flag;
    }

    @Override
    public Map<String, Object> selectSysUserByUserName(SysUserSelectReqDto sysUserSelectReqDto) {
        return sysUserMapper.selectSysUserByUserName(sysUserSelectReqDto);
    }

    @Override
    public Map<String, Object>  selectUserByUserName(SysUserSelectReqDto sysUserSelectReqDto) {
        SysUserSelectRespDto sysUserSelectRespDto = sysUserMapper.selectUserByUserName(sysUserSelectReqDto);
        Map<String, Object> map = new HashMap<>();
        map.put("user", sysUserSelectRespDto);
        return map;
    }
}
